#ifndef BYTEREADSTREAM_HPP
# define BYTEREADSTREAM_HPP

#ifdef DEBUG
    #include <cstdio>
    #include <iostream>
#endif

extern "C"{
    # include <sys/types.h>
    # include <features.h>
    # include <pcap.h>
}

// 按字节读数据的流结构
class ByteReadStream{
private:
    const char * content = NULL;
    uint32_t total;
    uint32_t read;

public:
    ByteReadStream(const char* buffer, uint32_t total)
     : content(buffer), total(total), read(0) { }

    ByteReadStream(ByteReadStream & other, uint32_t total){
        content = other.content + other.read;
        this->total = total;
        read = 0;
    }

    // 检查流中是否还有len这么多的数据
    inline uint32_t check_len(uint32_t len){
        if(read + len <= total)
            return 1;
        else return 0;
    }

    // 检查流中是否结束了,
    // 结束返回true，没结束返回false
    inline uint32_t is_end(){
        return read == total;
    }

    // 从流中读两个字节, 作为 uint32_t 类型返回，做了网络序到主机序的转换
    inline uint32_t read_int16(){
        uint32_t x = (*(content + read)) & 0x00ff;
        uint32_t y = (*(content + read + 1)) & 0x00ff;
        uint32_t sum = (x << 8) + y;
        read += 2;
        return sum;
    }

    // 从流中读一个字节
    inline uint32_t read_int8(){
        uint32_t x = (*(content + read)) & 0x00ff;
        read += 1;
        return x;
    }

    // 跳过流中 len 个字节
    inline void skip_len(uint32_t len){
        read += len;
    }

    // 从流中读 len 个字节, 到 dst字符数组 中，注意不能超过 dst字符数组的大小
    uint32_t read_str(char * dst, uint32_t len, uint32_t dst_max_size){
        uint32_t copy_cnt = (len < dst_max_size) ? len : dst_max_size - 1;
        for(uint32_t i = 0; i < copy_cnt; ++i){
            dst[i] = *(content + read + i);
        }
        dst[copy_cnt] = '\0';
        read += len;
        return copy_cnt;
    }

    // 返回六种要读取的下一个字节的位置
    inline const char * ret_pos(){
        return (content + read);
    }
};

#endif